/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package vn.com.pps.web.bean.common;

import java.awt.Desktop;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 *
 * @author Dai
 */
public class JasperReportBean {

    public static String JRTEMPLATE_PUPILLIST = "PupilList.jrxml";
    public static String JRTEMPLATE_BILL = "receipt.jrxml";


    public static String JRTEMPLATE_DIR = "D:\\Tools\\Friends\\report\\";
    public static String JRREPORTOUT_DIR = "D:\\Tools\\Friends\\report\\files\\";

    public static void printJRReport(HashMap parameters, String jrTemplateFile) throws Exception {
        /**
         * ******* SETUP **********
         */

        FacesContext fc = FacesContext.getCurrentInstance();

        ServletContext sc = (ServletContext) fc.getExternalContext()
                .getContext();

        WebApplicationContext wac = WebApplicationContextUtils
                .getWebApplicationContext(sc);

        DriverManagerDataSource connection = (DriverManagerDataSource) wac.getBean("dataSource");

        String fileNameOut = "";
        Connection con = connection.getConnection();

        try {
            System.out.println("Register connection to Database");
            HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
            httpServletResponse.addHeader("Content-disposition", "attachment; filename=Report.pdf");
            JasperReport report = JasperCompileManager.compileReport(JRTEMPLATE_DIR+ jrTemplateFile );
            System.out.println("Compile Report");
            JasperPrint jasperPrint = JasperFillManager.fillReport(report, parameters, con);
            FacesContext.getCurrentInstance().responseComplete();
            ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
            JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
            System.out.println("All done the report is done");
            servletOutputStream.flush();
            servletOutputStream.close();
            FacesContext.getCurrentInstance().responseComplete();
        } catch (JRException ex) {
            System.out.println("Jasper exception : ");
            //ex.printStackTrace();
        } catch (Exception ex) {
            System.out.println("Exception : ");
            //ex.printStackTrace();
        } finally {
            parameters = null;
            //close the connection.
            if (con != null) {
                try {
                    con.close();
                } catch (Exception ignored) {
                }
            }
        }

        /**
         * ******* SEND TO CLIENT **********
         */
        //FacesContext facesContext = FacesContext.getCurrentInstance();
        //HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        //response.setContentType("application/force-download");
        //response.addHeader("Content-Disposition", "attachment; filename=Report.docx");
        // FileOutputStream fileOut = null;
        /*
         FacesContext.getCurrentInstance().responseComplete();
         System.out.println("Test");
         try {
         File file = new File(fileNameOut);
         System.out.println("Report File:" + file.getAbsolutePath());
         System.out.println("Check Exist:" + file.exists());
         InputStream fis = new FileInputStream(file);
         byte[] buf = new byte[1024];
         int offset = 0;
         int numRead = 0;
         while ((offset < buf.length) && ((numRead = fis.read(buf, offset, buf.length - offset)) >= 0)) {
         offset += numRead;
         }
         fis.close();
         HttpServletResponse response
         = (HttpServletResponse) FacesContext.getCurrentInstance()
         .getExternalContext().getResponse();
         response.setContentType("application/pdf");
         response.setHeader("Content-Disposition", "attachment;filename=Report.pdf");
         response.getOutputStream().write(buf);
         response.getOutputStream().flush();
         response.getOutputStream().close();
         FacesContext.getCurrentInstance().responseComplete();
         } catch (Exception exc) {
         exc.printStackTrace();
         }
         */
    }
}
